package com.hdw.common.log;

import ch.qos.logback.classic.spi.CallerData;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.db.DBAppenderBase;
import com.hdw.common.base.api.BaseMsgService;
import com.hdw.common.base.service.BaseMsgServiceImpl;
import com.hdw.common.constant.CommonConstant;
import com.hdw.common.util.SpringBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;

@Configuration
public class LogDBAppender extends DBAppenderBase<ILoggingEvent> {

    protected static final Method GET_GENERATED_KEYS_METHOD;
    //插入sql
    protected String insertSQL;
    // message 日志内容
    static final int MESSAGE = 1;
    // level_string
    static final int LEVEL_STRING = 2;
    // created_time 时间
    static final int CREATE_TIME = 3;
    // logger_name 全类名
    static final int LOGGER_NAME = 4;
    static final int LOGGER_DES = 5;

    @Autowired
    private BaseMsgService baseMsgService;

    static final StackTraceElement EMPTY_CALLER_DATA = CallerData.naInstance();

    static {
        // PreparedStatement.getGeneratedKeys() method was added in JDK 1.4
        Method getGeneratedKeysMethod;
        try {
            // the
            getGeneratedKeysMethod = PreparedStatement.class.getMethod("getGeneratedKeys", (Class[]) null);
        } catch (Exception ex) {
            getGeneratedKeysMethod = null;
        }
        GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod;
    }

    @Override
    public void start() {
        // 将写好的sql语句赋值给insertSQL
        insertSQL = buildInsertSQL();
        super.start();
    }

    // 自己写新增sql语句
    private static String buildInsertSQL() {
        return "INSERT INTO `base_errlog`(`msg`,`level`,`dt_sys_cre`,`na_logger`,`des`)" +
                "VALUES (?,?,?,?,?)";
    }

    @Override
    protected Method getGeneratedKeysMethod() {
        return GET_GENERATED_KEYS_METHOD;
    }

    @Override
    protected String getInsertSQL() {
        return insertSQL;
    }

    @Override
    public void subAppend(ILoggingEvent event, Connection connection, PreparedStatement statement) throws Throwable {
        String level = event.getLevel().toString();
        if(!"ERROR".equals(level)) {
           return;
        }
        String message = event.getFormattedMessage();
        if(message.length()>255) {
            message = message.substring(0,255);
        }
        statement.setString(MESSAGE, message);
        statement.setString(LEVEL_STRING,level);
        statement.setTimestamp(CREATE_TIME, new Timestamp(event.getTimeStamp()));
        String naLogger = event.getLoggerName();
        if(naLogger.length()>255) {
            naLogger = naLogger.substring(0,255);
        }
        statement.setString(LOGGER_NAME,naLogger);
        String des = event.getThrowableProxy()==null?null:event.getThrowableProxy().getMessage();
        if(des!=null && des.length()>4000) {
            des = des.substring(0,4000);
        }
        statement.setString(LOGGER_DES, des);
        statement.executeUpdate();
    }

    @Override
    protected void secondarySubAppend(ILoggingEvent eventObject, Connection connection, long eventId) throws Throwable {
    }
}
